import http from 'http';
import qs from 'querystring';
import config from '../task/config'
import fs from 'fs'
import path from 'path'
import request from 'request'
const _readDir = (entry, ext) => {
  let filePaths = []
  const dirInfo = fs.readdirSync(entry)
  dirInfo.forEach(item => {
    const location = path.join(entry, item)
    const info = fs.statSync(location)
    if (info.isDirectory()) {
      filePaths = filePaths.concat(readDir(location, ext))
    } else {
      if (location.endsWith(ext)) {
        filePaths.push(location)
      }
    }
  })
  return filePaths
};


/**
 * 读取文件夹中所有文件方法
 * @param {String} path 
 * @param {String} ext
 * @return {Array} ['filePath']
 */
export const readDir = (dirPath, ext) => {
  return _readDir(dirPath, ext);
  // console.log(`\n readDir finished. `)
}


/**
 * httpGet基础方法
 * @param {*} options 
 */
const _httpGet = (options) => {

  const opt = {
    hostname: config.host,
    port: config.port,
    path: `${config.path}${options.url}`,
    method: 'GET',
    headers: options.headers || {
      'Content-Type': 'application/json; charset=UTF-8'
    }
  };
  // `http://${opt.hostname}:${opt.port}${opt.path}`
  var req = http.get(opt, function (res) {
    res.setEncoding('utf8');
    const contentType = res.headers['content-type']
    let responseText = ''
    res.on('data', (data) => {
      responseText = responseText + data
    });
    res.on('end', (e) => {
      // console.log(`get success.`)
      if (contentType.includes('json')) {
        options.success && options.success(JSON.parse(responseText));
      } else {
        options.success && options.success(responseText);
      }
    })
  });
  req.on('error', function (e) {
    options.error && options.error(e);
    console.log('problem with request: ' + e.message);
  });
  req.end();
}

/**
 * httpPost 基础方法
 * @param {*} options 
 */
const _httpPost = (options) => {
  //使用 querystirng 格式化
  var content = qs.stringify(options.data);
  const opt = {
    hostname: config.host,
    port: config.port,
    path: `${config.path}${options.url}`,
    method: 'POST',
    headers: options.headers || {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    protocol: 'http'
  };
  var req = http.request(opt, function (res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (response) {
      options.success && options.success(response);
      console.log('BODY: ' + response);
    });
  });
  req.on('error', function (e) {
    options.error && options.error(e);
    console.log('problem with request: ' + e.message);
  });
  req.write(content);
  req.end();
}

/**
 * HttpGet Promise 方法
 */
export const httpGet = (options) => {
  return new Promise((resolve, reject) => {
    options.success = (data) => {
      resolve(data);
    }
    options.error = (data) => {
      reject(data);
    }
    _httpGet(options);
  });
}


/**
 * HttpPost Promise 方法
 */
export const httpPost = (options) => {
  return new Promise((resolve, reject) => {
    options.success = (data) => {
      resolve(data);
    }
    options.error = (data) => {
      reject(data);
    }
    _httpPost(options);
  });
}



const _postFileToServer = (url, filePath, filename, dataKey, success, error) => {
  const sendUrl = `http://${config.host}:${config.port}${config.path}${url}`;
  request.post(sendUrl, {
    formData: {
      [dataKey]: fs.createReadStream(filePath)
    },
    json: true
  }, function (err, res, body) {
    if (err) {
      error(err)
    } else {
      if (!body) {
        success();
      }
    }
  })
}

/**
 * 上传文件
*/
export const postFile = (url, filePath, fileName, dataKey) => {
  return new Promise((resolve, reject) => {
    _postFileToServer(url, filePath, fileName, dataKey, resolve, reject);
  });
}

